<template>
  <div>
    <el-dialog
      title="Add variant image"
      :visible.sync="visible"
      width="630px"
      @close="emitClose"
    >
      <div class="imageBox">
        <div
          v-for="(item, index) in images"
          :key="index"
          :class="['item', selectedIndex === index ? 'selected' : '']"
        >
          <el-image
            :src="
              item.uri.indexOf('http') === 0
                ? item.uri
                : imgPrefix + item.uri + imgSuffix
            "
            @click="selectImg(item, index)"
          />
        </div>
        <div v-show="onCross" class="item loading">
          <i class="el-icon-loading" />
        </div>
        <el-upload
          action=""
          list-type="picture-card"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :http-request="uploadImg"
          :disabled="onCross"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="emitClose">Cancel</el-button>
        <el-button type="primary" @click="setVariantImg">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  props: {
    images: {
      type: Array,
      default: () => []
    },
    // eslint-disable-next-line vue/require-prop-types
    selectedId: {
      required: true
    },
    storeId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      visible: true,
      baseApi: process.env.VUE_APP_BASE_API,
      showImg: '',
      selectedItem: {},
      selectedIndex: null,
      onCross: false,
      nameLength: 100 // 图片名字最大长度
    };
  },
  mounted() {
    if (this.selectedId) {
      this.images.forEach((item, index) => {
        if (item.id === this.selectedId) {
          this.selectedItem = item;
          this.selectedIndex = index;
        }
      });
    }
  },
  methods: {
    beforeUpload(file) {
      // 仅有类型判断，未加大小判断
      const isIMG =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png';
      if (!isIMG) {
        this.$message.error(
          'Upload images only support JPG, jpeg, PNG format!'
        );
      }
      return isIMG;
    },
    uploadImg(params) {
      this.onCross = true;
      if (params.file.name.length > this.nameLength) {
        params.file.name = params.file.name.substring(
          params.file.name.length - this.nameLength
        );
      }
      this.params = {
        fileSize: params.file.size,
        storeId: this.storeId,
        name: params.file.name,
        categoryId: 0
      };
      const reader = new FileReader();
      reader.readAsDataURL(params.file);
      reader.onload = () => {
        this.showImage = true;
        this.params.fileContent = reader.result;
        axios({
          url: this.baseApi + '/erp/dealer/product/image/add',
          method: 'post',
          data: this.params,
          withCredentials: true,
          headers: { 'Content-Type': 'application/json;charset=UTF-8' }
        })
          .then(res => {
            this.onCross = false;
            if (res.data.code === 200) {
              const index = this.images.findIndex(
                item => item.id === res.data.data.id
              );
              if (index > -1) {
                this.$message.warning(
                  'The image already exists and cannot be added repeatedly'
                );
              } else {
                this.images.push(res.data.data);
              }
            } else {
              this.$message.error(res.data.message);
            }
          })
          .catch(error => {
            this.onCross = false;
            this.$message.error(error.message);
          });
      };
    },
    selectImg(item, index) {
      if (this.selectedIndex !== index) {
        this.selectedItem = item;
        this.selectedIndex = index;
      } else {
        this.selectedItem = {};
        this.selectedIndex = null;
      }
    },
    setVariantImg() {
      this.$emit('setVariantImg', this.selectedItem);
    },
    emitClose() {
      this.$emit('emitClose');
    }
  }
};
</script>

<style lang="scss" scoped>
.imageBox {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 110px;
    height: 110px;
    background: #f6f6f6;
    margin-left: 10px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    &.selected {
      border: 1px solid #409eff;
      transform: scale(0.8);
      &::before {
        position: absolute;
        bottom: 2px;
        right: -5px;
        z-index: 1;
        content: "";
        display: inline-block;
        font-weight: 700;
        margin: 0 10px;
        width: 8px;
        height: 13px;
        transform: rotate(45deg);
        border-style: solid;
        border-color: #409eff;
        border-width: 0 4px 4px 0;
      }
    }
    &.loading {
      text-align: center;
      line-height: 108px;
      font-size: 30px;
      color: #409eff;
    }
    &:nth-child(5n + 1) {
      margin-left: 0;
    }
  }
  ::v-deep .el-upload {
    width: 110px;
    height: 110px;
    line-height: 110px;
    margin-left: 10px;
    margin-bottom: 10px;
  }
}
</style>
